import { getToken } from "@/utils/auth"
import socketStore from "@/store/modules/socket"

//心跳包内容
let heartBeat = {
  event: "ping",
}
let pinkFn = null
export const initSocket = () => {
  window.WebSocket = window.WebSocket || window.MozWebSocket
  let ws = new WebSocket(`${import.meta.env.VITE_WEBSOCKET_HOST}socket/message/api/websocket?token=${getToken()}`)
  // let ws = new WebSocket(
  //   `${
  //     import.meta.env.VITE_WEBSOCKET_HOST
  //   }message/api/websocket?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIiLCJhdWQiOiIiLCJpYXQiOjE3MjA3OTM0OTUsIm5iZiI6MTcyMDc5MzQ5NSwiZXhwIjoxNzIwODc5ODk1LCJ0eXBlIjoxLCJkYXRhIjp7InVzZXJfaWQiOjQxNSwidGVuYW50X2lkIjoxLCJsb2dpbl90eXBlIjoxfX0.FaBVs6p0zolH2zih85o-Hlv5mo1LsTfM0MIZ_NFYMbs`
  // )

  ws.onopen = function () {
    console.log("Web Socket......")
    // Web Socket 已连接上，使用 send() 方法发送数据
    pinkFn = setInterval(function () {
      ws.send(JSON.stringify(heartBeat))
    }, 1000)
  }
  ws.onmessage = function (evt) {
    console.log("socket 数据已接收......")
    socketStore().setSocketStore(evt.data)
  }
  ws.onclose = function () {
    // 关闭 websocket
    clearInterval(pinkFn)
    pinkFn = null
    console.log("socket 连接已关闭......")
  }
  return ws
}
